package com.cqut.forum.service.imp;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.cqut.forum.dao.MessagesDao;
import com.cqut.forum.entity.Messages;
import com.cqut.forum.service.MessageService;
import com.cqut.forum.service.ModuleService;

@Component
public class MessageServiceImp implements MessageService {
	@Resource
	MessagesDao messageDao;
	@Resource
	ModuleService moduleService;
	
	@SuppressWarnings("deprecation")
	@Override
	public List<Map<String, Object>> getMessages(int userId, int index, int size) {
		//int moduleIndex = moduleService.getModuleIndex("留言");
		List<Map<String, Object>> messages = messageDao.getMessages(userId,index,size);
		List<Map<String, Object>> messageReplys = new ArrayList<Map<String,Object>>();
		if(messages.size()>0){
			List<Integer> messagesId = new ArrayList<Integer>();
			for(Map<String, Object> m:messages){
				messagesId.add((Integer)m.get("messages_id"));
			}
			messageReplys = messageDao.getMessageReply(messagesId);
		}
		
		List<Map<String, Object>> result = new ArrayList<Map<String,Object>>();
		
		for(Map<String, Object> map:messages){
			Map<String,Object> m = new HashMap<String, Object>();
			m.put("userId", map.get("user_id"));
			m.put("image", map.get("user_photo"));
			m.put("name", map.get("user_name"));
			m.put("content", map.get("messages_contents"));
			m.put("time", ((Date)map.get("messages_time")).toLocaleString());
			m.put("messageId", map.get("messages_id"));
			List<Map<String, Object>> reply = new ArrayList<Map<String,Object>>();
			for(Map<String, Object> r:messageReplys){
				if(map.get("messages_id").equals(r.get("above_messages_id"))){
					Map<String, Object> rep = new HashMap<String, Object>();
					rep.put("userId", r.get("user_id"));
					rep.put("image", r.get("user_photo"));
					rep.put("name", r.get("user_name"));
					rep.put("content", r.get("messages_contents"));
					rep.put("time", ((Date)r.get("messages_time")).toLocaleString());
					reply.add(rep);
				}
			}
			m.put("reply", reply);
			
			result.add(m);
		}
		return result;
	}

	@Override
	public boolean haveReadMyMessages(int userId, String moduleName) {
		//int moduleId = moduleService.getModuleIndex(moduleName);
		boolean result = messageDao.haveReadMyMessages(userId);
		return result;
	}

	@Override
	public Messages getMessageById(int messageId) {
		Messages m = messageDao.get(messageId, Messages.class);
		return m;
	}

	@Override
	public Messages saveMessage(Messages message) {
		message = messageDao.save(message);
		return message;
	}

	@Override
	public Messages updateMessage(Messages message) {
		message = messageDao.update(message);
		return message;
	}

}
